package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.ReportMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.Data;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;

@Service
@Data
public class ReportServiceImpl implements ReportService {

    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private WorkspaceService workspaceService;

//营业额统计
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        TurnoverReportVO turnoverReportVO = new TurnoverReportVO();
        List<LocalDate> localDateList = new ArrayList<>();
        List<Double> turnoverList = new ArrayList<>();
        localDateList.add(begin);

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);
        Double turnover = reportMapper.sumTurnover(Orders.COMPLETED,beginTime,endTime);//第一天的营业额
        turnover = turnover == null ? 0 : turnover;
        turnoverList.add(turnover);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDateList.add(begin);//将日期遍历到列表里
            //计算每日营业额
            beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            endTime = LocalDateTime.of(begin, LocalTime.MAX);
            turnover = reportMapper.sumTurnover(Orders.COMPLETED,beginTime,endTime);
            turnover = turnover == null ? 0 : turnover;
            turnoverList.add(turnover);
        }
        String dateList = StringUtils.join(localDateList,",");
        String turnOver = StringUtils.join(turnoverList,",");
        turnoverReportVO.setDateList(dateList);
        turnoverReportVO.setTurnoverList(turnOver);
        return turnoverReportVO;
    }
//用户统计
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateList = new ArrayList<>();//日期
        List<Integer> newUserList = new ArrayList<>();//新用户
        List<Integer> allUserList = new ArrayList<>();//所有用户
        localDateList.add(begin);//添加第一天日期

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);
        Integer newUser = reportMapper.sumNewUser(beginTime,endTime);
        Integer allUser = reportMapper.sumAllUser(endTime);
        newUser = newUser == null ? 0 : newUser;
        allUser = allUser == null ? 0 : allUser;
        newUserList.add(newUser);//第一天的用户量
        allUserList.add(allUser);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDateList.add(begin);//将日期遍历到列表里
            //计算每日用户
            beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            endTime = LocalDateTime.of(begin, LocalTime.MAX);
            newUser = reportMapper.sumNewUser(beginTime,endTime);
            allUser = reportMapper.sumAllUser(endTime);
            newUser = newUser == null ? 0 : newUser;
            allUser = allUser == null ? 0 : allUser;
            newUserList.add(newUser);
            allUserList.add(allUser);
        }
        return new UserReportVO(
                StringUtils.join(localDateList,","),
                StringUtils.join(allUserList,","),
                StringUtils.join(newUserList,","));
    }
//订单统计
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDateList = new ArrayList<>();//日期
        List<Integer> orderCountList = new ArrayList<>();//订单数
        List<Integer> validOrderCountList = new ArrayList<>();//有效订单数
        localDateList.add(begin);//添加第一天日期

        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(begin, LocalTime.MAX);
        Integer orderCount = reportMapper.sumAllOrder(beginTime,endTime);
        Integer validOrderCount = reportMapper.sumValidOrder(beginTime,endTime,Orders.COMPLETED);
        orderCount = orderCount == null ? 0 : orderCount;
        validOrderCount = validOrderCount == null ? 0 : validOrderCount;
        orderCountList.add(orderCount);//第一天的订单数
        validOrderCountList.add(validOrderCount);//第一天的有效订单数
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            localDateList.add(begin);//将日期遍历到列表里
            //计算每日订单
            beginTime = LocalDateTime.of(begin, LocalTime.MIN);
            endTime = LocalDateTime.of(begin, LocalTime.MAX);
            orderCount = reportMapper.sumAllOrder(beginTime,endTime);
            validOrderCount = reportMapper.sumValidOrder(beginTime,endTime,Orders.COMPLETED);
            orderCount = orderCount == null ? 0 : orderCount;
            validOrderCount = validOrderCount == null ? 0 : validOrderCount;
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
        Integer totalOrderCount = reportMapper.sumOrder();//整店订单总数
        Integer validOrderCounts = reportMapper.sumVOrder(Orders.COMPLETED);//整店有效订单数
        Double orderCompletionRate = Double.valueOf(validOrderCounts/totalOrderCount);//订单有效率
        return new OrderReportVO(
                StringUtils.join(localDateList,","),
                StringUtils.join(orderCountList,","),
                StringUtils.join(validOrderCountList,","),
                totalOrderCount,validOrderCounts,orderCompletionRate
        );
    }
//top10商品
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOS = reportMapper.top10(beginTime,endTime);//查出名字和销量
        List<String> name = new ArrayList<>();
        List<Integer> number = new ArrayList<>();
        for (GoodsSalesDTO goodsSalesDTO: goodsSalesDTOS){//分别放到两个列表
            name.add(goodsSalesDTO.getName());
            number.add(goodsSalesDTO.getNumber());
        }
        return new SalesTop10ReportVO(
                StringUtils.join(name,","),
                StringUtils.join(number,",")
        );
    }
//30天数据导出
    @Override
    public void export(HttpServletResponse httpServletResponse) {
        //读取数据
        LocalDate dateBegin = LocalDate.now().minusDays(30);
        LocalDate dateEnd = LocalDate.now().minusDays(1);

        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateEnd, LocalTime.MAX));
        //通过POI将数据写入文件
        //InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            InputStream in = new FileInputStream(new File("C://Users/linchuncheng/Desktop/苍穹外卖/苍穹外卖/资料/day12/运营数据报表模板.xlsx"));
            XSSFWorkbook excel = new XSSFWorkbook(in);
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //总览数据
            sheet.getRow(1).getCell(1).setCellValue("时间："+dateBegin+"--"+dateEnd);
            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());
            //每日数据
            for (int i = 0; i < 30; i++){
                businessData = workspaceService.getBusinessData(LocalDateTime.of(dateBegin, LocalTime.MIN), LocalDateTime.of(dateBegin, LocalTime.MAX));
                sheet.getRow(7+i).getCell(1).setCellValue(String.valueOf(dateBegin));
                sheet.getRow(7+i).getCell(2).setCellValue(businessData.getTurnover());
                sheet.getRow(7+i).getCell(3).setCellValue(businessData.getValidOrderCount());
                sheet.getRow(7+i).getCell(4).setCellValue(businessData.getOrderCompletionRate());
                sheet.getRow(7+i).getCell(5).setCellValue(businessData.getUnitPrice());
                sheet.getRow(7+i).getCell(6).setCellValue(businessData.getNewUsers());
                dateBegin = dateBegin.plusDays(1);
            }
            //通过输出流将excel写回到浏览器
            ServletOutputStream out = httpServletResponse.getOutputStream();
            excel.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
